package org.slg.oracleproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slg.oracleproject.entity.Permission;
import org.slg.oracleproject.entity.Role;
import org.slg.oracleproject.mapper.PermissionMapper;
import org.slg.oracleproject.mapper.RoleMapper;
import org.slg.oracleproject.mapper.RolePermissionMapper;
import org.slg.oracleproject.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  服务层实现。
 *
 * @author 沙龙果
 * @since 2025年09月23日
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;


    /**
     * 根据用户角色获取对应的接口权限
     * @param roleNames
     * @return
     */
    @Override
    public List<String> getPermissionsByRoles(List<String> roleNames) {
        // 1. 根据角色名查询角色ID（如"USER" -> ID=1，"SUPER_ADMIN" -> ID=2）
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_name", roleNames);
        List<Role> roles = roleMapper.selectList(queryWrapper);
        if (roles.isEmpty()) {
            return Collections.emptyList(); // 没有对应角色，返回空权限
        }
        // 2. 提取角色ID列表
        List<Integer> roleIds = roles.stream()
                .map(Role::getId)
                .collect(Collectors.toList());
        return this.permissionMapper.findPermCodesByRoleIds(roleIds);
    }
}
